(function () {
	//添加菜单，弹出弹窗
    jQuery('.addBtn').on('click', function () {
    	jQuery('#id').val('');
        jQuery('#levelNameNew').val('');
        jQuery('#levelOrderNew').val('');
        jQuery('#bussinessLevelModal').modal('show');
    });
    //查询
    jQuery('.searchBtn').on('click',function(){
        serverData.key=jQuery('#search').val();
        serverTable.draw();
    })

    //撤销查询
    jQuery('.resetBtn').on("click",function(){
        jQuery('#search').val('');
        serverData.key ='';
        serverTable.draw();
    });
    //table数据显示
    var serverData = {};
    var	serverTable;
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/bussinessLevel/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [{
                data: null,
                defaultContent: ""
            },
                {
                    data: 'levelName'
                },
                {
                    data: 'levelOrder'
                },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate ='<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>';

                        return operate;

                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-remove')!=-1 || target.className.indexOf('delBtn')!=-1){

                        deleteBussinessLevel(data);
                    }

                    if(target.className.indexOf('fa-pencil')!=-1||target.className.indexOf('editBtn')!=-1){

                        editBussinessLevel(data);
                    }
                    if(target.className.indexOf('fa-sign-in')!=-1||target.className.indexOf('addNode')!=-1){

                        setNode(data,data.levelName);
                    }
                    return;
                } );
            }
        });
        
        var deleteBussinessLevel=function(data){
            if(!data) return;
            $.springLemonDialog({
                content:'确认模块：'+data.levelName+'？',//确认文本
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+"/ui/bussinessLevel/delete/"+data.id;
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type : "post",
                            dataType:"json",
                            success:function(data){
                                serverTable.draw(false);
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }

            });

        };
        var editBussinessLevel=function(data){
            if(!data) return;
            jQuery('#id').val(data.id);
            jQuery('#levelNameNew').val(data.levelName);
            jQuery('#levelOrderNew').val(data.levelOrder);
            jQuery('#bussinessLevelModal').modal('show');
        };
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#search').val();
            serverTable.draw();
        })
        //撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#search').val('');
            serverData.key ='';
            serverTable.draw();
        });
        //新增，编辑保存
        jQuery('.saveBtn').on('click',function(){
            if(jQuery("#bussinessLevelEditForm") && !jQuery("#bussinessLevelEditForm").Validform({tiptype:3, showAllError:true}).check(false)){
                return;
            };
            
            var data={
                    id:jQuery('#id').val(),
                    levelName:jQuery('#levelNameNew').val(),
                    levelOrder:jQuery('#levelOrderNew').val(),
                };
                var url=window.rootPath+'/ui/bussinessLevel/save';
                jQuery.ajax({
                    url:encodeURI(url),
                    type:'post',
                    data:JSON.stringify(data),
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    success: function () {
                        jQuery('#bussinessLevelModal').modal('hide');
                        serverTable.draw(false);
                    }
                });
        });

    });

    ////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: true,
            showRemoveBtn:setRemoveBtn,
            showRenameBtn:false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: true,
			chkStyle: "radio",
			radioType: "level"
		},
        callback:{
            beforeRemove: beforeRemove,
            onRemove:onRemove,
            onCheck:editNewModule
        }

    };
    
    //菜单树点击编辑节点
    function editNewModule(e, treeId, treeNode){
    	var Id=treeNode.id;
        var url=window.rootPath +'/ui/bussinessLevel/getNode'+'?Id='+Id;
        jQuery.ajax({
            url:url,
            cache:false,
            type :"get",
            dataType:"json",
            contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
            success:function(data){
            	jQuery('#id1').val(data.node.id);
                jQuery('#levelNameNew1').val(data.node.levelName);
                jQuery('#levelOrderNew1').val(data.node.levelOrder);
                jQuery('#bussinessLevelModal1').modal('show');   
            }
        });	
    }
    
    
    //删除按钮的设置
    function setRemoveBtn(treeId, treeNode) {
        //判断为顶级节点则不显示删除按钮
        if(treeNode.level == 0)
            return false;
        else
            return true;

    }
    var menuId="1";
    var primaryNode=[];
    var url = window.rootPath +'/ui/bussinessLevel/getAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        data:{
            "menuId":menuId
        },
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
                primaryNode.push(
                    {
                        id: 0,
                        name: "模型树",
                        open: "true"
                        // iconSkin:"diy03"
                    }
                );
                for (var i = 0; i < data.nodes.length; i++) {
                    primaryNode.push(data.nodes[i]);
                }
            $.fn.zTree.init($("#bussinessLevelTree"),modalSetting,primaryNode);
        }
    });
    //////////////////删除节点/////////////////////////////
    function beforeRemove(treeId, treeNode) {
        return confirm("确认删除 " + treeNode.name + "节点 吗？");
    }
    function onRemove(e, treeId, treeNode) {
        //此处treeNode 为当前节点,
        var str ='' ;
        var selectPId=treeNode.getParentNode().id;
        var url=window.rootPath+'/ui/bussinessLevel/deleteNodes';
        str=treeNode.id;
        str = getAllChildrenNodes(treeNode,str);//获得所有id的字符串，方法在myTree.js
        var d = {
                "str":str,
                "selectPId":selectPId
            }
        jQuery.ajax({
            url:encodeURI(url),
            type :"post",
            data:JSON.stringify(d),
            dataType:"json",
            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
            success:function(data){
                serverTable.draw(false);
            }
        });
    }

    ////////////////添加节点///////////////////////////////
    function setNode(data,levelName){
        var treeObj= $.fn.zTree.getZTreeObj("bussinessLevelTree");
        var selectNodes=treeObj.getSelectedNodes(treeObj);
        var selectNode=selectNodes[0];
        var levelName=levelName;
        if(selectNode){
            $.springLemonDialog({
                title:'系统提示',//标题   默认为   系统提示
                content:'是否要绑定'+levelName+'节点？',//确认文本
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+'/ui/bussinessLevel/saveNode';
                        var d = {
                                "levelPId":selectNode.id,
                                "id":data.id
                            };
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type :"post",
                            data: JSON.stringify(d),
                            dataType:"json",
                            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
                            success:function(data){
                                if(data.code==1){
                                    var newNode={
                                        "id": data.BussinessLevel.id,
                                        "parentId":selectNode.id,
                                        "name":levelName
                                        //   iconSkin:"diy05"

                                    }
                                    selectNode=treeObj.addNodes(selectNode,newNode);
                                    serverTable.draw(false);
                                }
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }
            });
        }
        else{
            $.springLemonDialog({
                title:'系统提示',//标题   默认为   系统提示
                content:'请选择一个节点',//确认文本
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    $(this).closeDialog(modal);
                }

            });
        }
    }

})();